<?php
/**
 * AJAX Handler for Contrib: Del - Delete Contributors from a project
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    $_ECLIPSEMDE = array();
    
    // Disable Templating System
    $_ECLIPSEMDE['TEMPLATING'] = false;
    require_once('../../SiteIncludes.GLOBAL.php');
    
    // Tell libdebug to never print out error information - overrides debugging flags in fwork
    $_LIBDEBUG->silence();
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
    
    // Ensure all variables needed are set
    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && isset($gVAR['alias']) !== false && isset($gVAR['user']) !== false) {
	try {
	    $Project =& $ProjectStash->get($gVAR['alias']);
	    
	    if($Project->userCanEdit($_LOGGEDINUSER->get_userid()) === true) {
		$safe_un = $sql_conx->real_escape_string($gVAR['user']);
		$ProjectUsers = $Project->getNoneLeaderMaintainers();
		$cb_error = false;
		if(in_array((int)$gVAR['user'], $ProjectUsers)) {
		    if($_LOGGEDINUSER->get_userid() != (int)$gVAR['user']) {
			$query = $sql_conx->query("DELETE FROM `tool_maintainers` WHERE `pid`='{$Project->getID()}' AND `uid`='{$safe_un}' LIMIT 1");
			if($sql_conx->affected_rows === 0) {
			    $cb_error = "That user is not a maintainer.";
			} else {
			    $cb_error = false;
			}
		    } else {
			$cb_error = "You cannot delete yourself. Please leave the project instead.";
		    }
		} else {
		    if($Project->getLeadMaintainer() == $gVAR['user']) {
			$cb_error = "Lead maintainer cannot be deleted.";
		    } else {
			$cb_error = "That user is not a maintainer.";
		    }
		}
		echo <<<EOHEAD
		    <!DOCTYPE html>
			<head><title></title></head>
			<body>
			<script type="text/javascript">
EOHEAD;
		if($cb_error === false) {
		    $Project->updateWrite($_LOGGEDINUSER->get_userid(), ($Project->userCanAdmin($_LOGGEDINUSER->get_userid(), false) === true ? ProjectEditType::DelMaintainer : ProjectEditType::AdminDelMaintainer), array($safe_un));
		    echo <<<EOBODY
			parent.UserContribEDJX.delError(false);
			parent.EDJXConfirmer.show_ok();
EOBODY;
		} else {
		    echo <<<EOBODY
			parent.UserContribEDJX.delError('{$cb_error}');
			parent.EDJXConfirmer.show_nok();
EOBODY;
		}
		echo <<<EOTAIL
			</script>
			</body>
		    </html>
EOTAIL;
	    } else {
		throw new InvalidProjectException();
	    }
	} catch(InvalidProjectException $e) {
	    header("HTTP/1.1 400 Bad Request");
	    die($nok_caller);
	}
    } else {
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
?>